<!--
 * @Author: 雷宇航
 * @Date: 2021-07-16 10:31:48
 * @LastEditTime: 2021-08-11 11:16:43
 * @LastEditors: 雷宇航
 * @Description:
 * @FilePath: \icm\icm-vue\src\views\hifar\contract\ReturnMoneyManagementList.vue
-->
<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper ReturnMoneyManagementList'>
      <a-form layout='inline' @keyup.enter.native='searchQuery'>
        <a-row :gutter='24'>
          <a-col :xl='24' :lg='7' :md='8' :sm='24'>
            <a-radio-group v-model='queryParam.returnStatus' @change='radioChange'>
              <a-form-item label='回款状态'>
                <a-radio :value='3'>本年未回</a-radio>
                <a-radio :value='4'>本年已回</a-radio>
                <a-radio :value='0'>未回</a-radio>
                <a-radio :value='1'>已回</a-radio>
                <a-radio :value='2'>全部</a-radio>
              </a-form-item>
            </a-radio-group>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='客户简称'>
              <a-input placeholder='请输入客户简称' v-model='queryParam.customerName'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='合同编号'>
              <a-input placeholder='请输入合同编号' v-model='queryParam.contractNum'></a-input>
            </a-form-item>
          </a-col>
          <template v-if='toggleSearchStatus'>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='合同名称'>
                <a-input placeholder='请输入合同名称' v-model='queryParam.contractName'></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='销售经理'>
                <a-input placeholder='请输入销售经理' v-model='queryParam.salesman'></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='回款负责人'>
                <a-input placeholder='请输入回款负责人' v-model='queryParam.paymantCharger'></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='项目经理'>
                <a-input placeholder='请输入项目经理' v-model='queryParam.projectManager'></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='6' :md='8' :sm='12'>
              <a-form-item label='计划回款时间'>
                <j-date
                  placeholder='请选择开始日期'
                  class='query-group-cust'
                  v-model='queryParam.expectTime_begin'
                ></j-date>
                <span class='query-group-split-cust'></span>
                <j-date
                  placeholder='请选择结束日期'
                  class='query-group-cust'
                  v-model='queryParam.expectTime_end'
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='6' :md='8' :sm='12'>
              <a-form-item label='实际回款时间'>
                <j-date
                  placeholder='请选择开始日期'
                  class='query-group-cust'
                  v-model='queryParam.actualTime_begin'
                ></j-date>
                <span class='query-group-split-cust'></span>
                <j-date
                  placeholder='请选择结束日期'
                  class='query-group-cust'
                  v-model='queryParam.actualTime_end'
                ></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='float: left; overflow: hidden' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
              <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
      <a-button
        type='primary'
        icon='download'
        @click="handleExportXls('回款管理')"
        v-has="'ContractSalePaymentCollection:export'"
      >导出
      </a-button
      >
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :scroll='{ x: true }'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        :loading='loading'
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
        @change='handleTableChange'
      >
         <template slot="ratioMoney" slot-scope="text, record">
          <span>{{ record.actualMoney / record.contractMoney == 0 ?  0+'%' :((record.actualMoney / record.contractMoney)*100).toFixed(2) + '%'  }}</span>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px; font-style: italic'>无图片</span>
          <img
            v-else
            :src='getImgView(text)'
            height='25px'
            alt=''
            style='max-width: 80px; font-size: 12px; font-style: italic'
          />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px; font-style: italic'>无文件</span>
          <a-button v-else :ghost='true' type='primary' icon='download' size='small' @click='downloadFile(text)'>
            下载
          </a-button>
        </template>
        <template slot='action' slot-scope='text, record' v-if="record.contractBpmStatus === '3'">
          <!--销售/项目负责人，申请发票-->
          <div>
            <a v-has="'ReturnMoney:edit'" @click='returnMoneyManagemenEdit(record)'>编辑</a>
            <a-divider type='vertical' v-has="'ReturnMoney:edit'" />
            <a v-if="record.bpmStatus === '1'" @click='saleApplyInvoiceHandleDetail(record, false)'>申请</a>
            <template v-if='record.auditDataId'>
              <a-divider type='vertical' v-if="record.auditDataId && record.bpmStatus === '1'" />
              <a-dropdown>
                <a class='ant-dropdown-link'>更多
                  <a-icon type='down' />
                </a>
                <a-menu slot='overlay'>
                  <a-menu-item>
                    <a @click='saleApplyInvoiceHandleDetail(record, true)'>详情</a>
                  </a-menu-item>
                  <a-menu-item v-if="record.bpmStatus === '1'">
                    <a @click='startApplyInvoiceProcess(record)'>发起流程</a>
                  </a-menu-item>
                  <a-menu-item v-if="record.bpmStatus !== '1'" @click='handleTrack(record)'>审批进度</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </div>
          <!-- 财务，回款确认 -->
          <div v-has="'ContractSalePaymentCollection:sure'">
            <a v-if='record.auditDataId' @click='saleApplyInvoiceHandleDetail(record, true)'>详情</a>
            <a-divider type='vertical' v-if='record.auditDataId' />
            <a @click='handleEdit(record)'>确认</a>
          </div>
        </template>
      </a-table>
      <a-row>
        <a-col :span='12'>
          <a-card>
            <a-statistic title='计划回款金额（元）' :value='countExpectMoney' />
          </a-card>
        </a-col>
        <a-col :span='12'>
          <a-card>
            <a-statistic title='实际回款金额（元）' :value='countActualMoney' />
          </a-card>
        </a-col>
      </a-row>
    </div>
    <bus-business-opportunity-change-list
      :mainId='selectedMainId'
      :dataType="'ContractSalePaymentCollection'"
      ref='updateShow'
    />
    <ReturnMoneyManagementModal ref='returnMoneyManagemenModalForm' @ok='modalFormOk'></ReturnMoneyManagementModal>
    <contract-sale-payment-collection-modal ref='modalForm' @ok='modalFormOk'></contract-sale-payment-collection-modal>
    <contract-sale-apply-invoice-modal
      ref='saleApplyInvoiceModalForm'
      @ok='saleApplyInvoiceOk'
    ></contract-sale-apply-invoice-modal>
    <bpm-process-track-modal ref='bpmProcessTrackModal'></bpm-process-track-modal>
    <bpm-biz-task-deal-modal
      ref='taskDealModal'
      :path='path'
      :formData='formData'
      @ok='handleOk'
    ></bpm-biz-task-deal-modal>
  </a-card>
</template>

<script>
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import { getAction, postAction } from '@/api/manage'
import BpmBizTaskDealModal from '@views/modules/bpmbiz/common/BpmBizTaskDealModal'
import BpmProcessTrackModal from '@views/modules/bpmbiz/common/BpmProcessTrackModal'
import ContractSalePaymentCollectionModal from './modules/ContractSalePaymentCollectionModal'
import ContractSaleApplyInvoiceModal from '@views/hifar/contract/modules/ContractSaleApplyInvoiceModal'
import ReturnMoneyManagementModal from '@views/hifar/contract/modules/ReturnMoneyManagementModal'
import BusBusinessOpportunityChangeList from '@views/hifar/business/BusBusinessOpportunityChangeList'
import { JeecgBpmListMixin } from '@/mixins/JeecgBpmListMixin'
import { toFixedTwo } from '@/utils/util'
import store from '@/store'
import { sorter } from '@/utils/sorter'

export default {
  name: 'ContractSaleList',
  mixins: [JeecgBpmListMixin],
  components: {
    ContractSalePaymentCollectionModal,
    ContractSaleApplyInvoiceModal,
    BpmBizTaskDealModal,
    BpmProcessTrackModal,
    ReturnMoneyManagementModal,
    BusBusinessOpportunityChangeList
  },
  data() {
    return {
      description: '回款管理页面',
      radioStyle: {
        // lineHeight: '32px',
      },
      countExpectMoney: 0,
      countActualMoney: 0,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '合同编号',
          align: 'center',
          dataIndex: 'contractNum',
          scopedSlots: { customRender: 'contractNum' }
        },
        {
          title: '合同名称',
          align: 'center',
          dataIndex: 'contractName'
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerName'
        },
        {
          title: '合同金额',
          align: 'right',
          dataIndex: 'contractMoney',
          sorter: sorter('contractMoney'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '销售经理',
          align: 'center',
          dataIndex: 'salesman'
        },
        {
          title: '售前经理',
          align: 'center',
          dataIndex: 'preSaleLeader'
        },
        {
          title: '项目经理',
          align: 'center',
          dataIndex: 'projectManager'
        },
        {
          title: '回款条件',
          align: 'center',
          dataIndex: 'returnCondition_dictText'
        },
        {
          title: '计划回款金额',
          align: 'right',
          dataIndex: 'expectMoney',
          sorter: sorter('expectMoney'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '计划回款时间',
          align: 'center',
          dataIndex: 'expectTime',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          defaultSortOrder: 'ascend',
          sorter: (a, b) => a.expectTime - b.expectTime
        },
        {
          title: '回款负责人',
          align: 'center',
          dataIndex: 'paymantCharger'
        },
        {
          title: '实际回款金额',
          align: 'right',
          dataIndex: 'actualMoney',
          sorter: sorter('actualMoney'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '回款比例',
          align: 'right',
          dataIndex: 'ratioMoney',
          sorter: sorter('ratioMoney'),
          scopedSlots: { customRender: 'ratioMoney' }
        },
        {
          title: '实际回款时间',
          align: 'center',
          dataIndex: 'actualTime',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          defaultSortOrder: 'descend',
          sorter: (a, b) => a.actualTime - b.actualTime
        },
        {
          title: '是否开票',
          align: 'center',
          dataIndex: 'billing_dictText'
        },
        {
          title: '开票比例',
          align: 'center',
          dataIndex: 'billingRatio'
        },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      queryParam: {
        returnStatus: 3, //默认回款状态为本年未回
        contractBpmStatus: '3' //查询审核通过后的合同
      },
      isorter: {
        order: 'asc',
        column: 'expectTime'
      },
      url: {
        list: '/contract/contractSalePaymentCollection/list',
        sum: '/contract/contractSalePaymentCollection/sum',
        delete: '/contract/contractSalePaymentCollection/delete',
        deleteBatch: '/contract/contractSalePaymentCollection/deleteBatch',
        exportXlsUrl: '/contract/contractSalePaymentCollection/exportXls',
        importExcelUrl: 'contract/contractSalePaymentCollection/importExcel',
        queryById: 'contract/contractSalePaymentCollection/queryById',
        findByPaymentId: '/contract/contractSaleApplyInvoice/findByPaymentId',
        startProcess: '/act/process/extActProcess/startMutilProcess'
      },
      flowCode: 'dev_hf_contract_sale_apply_invoice_001',
      dictOptions: {},
      flag: true,
      queryModel: true
    }
  },
  created() {
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    returnMoneyManagemenEdit(record) {
      this.$refs.returnMoneyManagemenModalForm.edit(record)
      this.$refs.returnMoneyManagemenModalForm.title = '编辑'
      this.$refs.returnMoneyManagemenModalForm.disableSubmit = false
    },
    searchReset() {
      this.queryParam = {}
      this.queryParam.returnStatus = 3
      this.queryParam.contractBpmStatus = '3'
      this.loadData(1)
    },
    radioChange() {
      if (this.queryParam.returnStatus == 0) {
        this.isorter = {
          order: 'asc',
          column: 'expectTime'
        }
      } else if (this.queryParam.returnStatus == 1) {
        this.isorter = {
          order: 'desc',
          column: 'actualTime'
        }
      }
      this.loadData()
    },
    refresh(row) {
      this.queryParam.contractId = row.id
      this.loadData(1)
    },
    saleApplyInvoiceHandleDetail(record, disableSubmit) {
      let saleApplyInvoice = {}
      let that = this

      getAction(this.url.findByPaymentId, { id: record.id }).then((res) => {
        if (res.success) {
          saleApplyInvoice = res.result
          that.$refs.saleApplyInvoiceModalForm.edit(saleApplyInvoice)
          that.$refs.saleApplyInvoiceModalForm.title = '销售合同开票信息'
          that.$refs.saleApplyInvoiceModalForm.disableSubmit = disableSubmit
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleEdit(record) {
      let that = this
      getAction(this.url.queryById, { id: record.id }).then((res) => {
        if (res.success) {
          this.$refs.modalForm.edit(res.result)
          this.$refs.modalForm.title = '回款确认'
          this.$refs.modalForm.disableSubmit = false
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.id.split(','), [record])
          }
        }
      }
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.selectedMainId = ''
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0]
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    startApplyInvoiceProcess(record) {
      this.$confirm({
        title: '提示',
        content: '确认提交流程吗?',
        onOk: () => {
          let params = {
            flowCode: this.flowCode,
            id: record.auditDataId,
            formUrl: 'hifar/contract/modules/ContractSaleApplyInvoiceForm',
            formUrlMobile: ''
          }
          postAction(this.url.startProcess, params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.loadData()
                this.onClearSelected()
              } else {
                this.$message.warning(res.message)
              }
            })
            .catch((e) => {
              this.$message.warning('不识别的请求!')
            })
        }
      })
    },

    handleTrack(record) {
      var params = { flowCode: this.flowCode, dataId: record.auditDataId } //查询条件
      this.$refs.bpmProcessTrackModal.handleTrack(params)
      this.$refs.bpmProcessTrackModal.title = '审批跟踪记录'
    },

    saleApplyInvoiceOk() {
      this.loadData(1)
    },
    getSum() {
      var params = this.getQueryParams() //查询条件
      getAction(this.url.sum, params).then((res) => {
        if (res.success) {
          this.countExpectMoney = toFixedTwo(res.result.countExpectMoney) || 0
          this.countActualMoney = toFixedTwo(res.result.countActualMoney) || 0
        }
      })
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.onClearSelected()
      this.getSum()
      var params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style>
.ReturnMoneyManagementList .ant-radio-group {
  display: block;
}
</style>
